import fs from 'fs';
import { fileURLToPath, URL } from 'node:url';

import { defineConfig, loadEnv } from 'vite';

import { createBuildConfig } from './scripts/create-build';
import { createCssConfig } from './scripts/create-css';
import { createServerConfig } from './scripts/create-server';
import { createVitePlugins } from './scripts/plugins';

const optimizeDepsHivePlusIncludes: string[] = []; // hive-plus/es 开发环境，主动加载所有有样式，防止加载新组件时页面刷新

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  // 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀。
  const env = loadEnv(mode, process.cwd(), '');
  const viteVisualizer = env.VITE_VISUALIZER === 'true';

  const plugins = createVitePlugins(env, {
    iconDirs: [fileURLToPath(new URL('./src/assets/svg', import.meta.url))],
    customDomId: '__mh__svg__icons__dom__',
    viteVisualizer,
  });

  if (env.NODE_ENV === 'development') {
    fs.readdirSync("node_modules/hive-plus/es/components").map((dirname) => {
      optimizeDepsHivePlusIncludes.push(
        `hive-plus/es/components/${dirname}/style/index`
      );
    });
  }

  return {
    base:'/',
    publicDir: env.VITE_APP_PUBLIC_DIR,
    optimizeDeps: {
      include: optimizeDepsHivePlusIncludes,
    },
    plugins,
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
      // 类型： string[] 导入时想要省略的扩展名列表。
      extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue', '.mjs'],
    },
    css: createCssConfig(),
    build: createBuildConfig(env),
    server: createServerConfig(env),
  };
});
